package model

import (
	"sync"
	"time"

	"github.com/ezbuy/redis-orm/orm"
	"github.com/ezbuy/wrapper/database"
)

var (
	_mssql_store *orm.DBStore
	_mssql_cfg   MsSQLConfig
	_mssql_once  sync.Once
)

type MsSQLConfig struct {
	Host            string
	Port            int
	UserName        string
	Password        string
	Database        string
	PoolSize        int
	ConnMaxLifeTime time.Duration
}

func MsSQLSetup(cf *MsSQLConfig) {
	_mssql_cfg = *cf
}

func MsSQL() *orm.DBStore {
	var err error
	_mssql_once.Do(func() {
		_mssql_store, err = orm.NewDBStore("mssql",
			_mssql_cfg.Host,
			_mssql_cfg.Port,
			_mssql_cfg.Database,
			_mssql_cfg.UserName,
			_mssql_cfg.Password)
		if err != nil {
			panic(err)
		}
		_mssql_store.SetConnMaxLifetime(time.Hour)
		if _mssql_cfg.ConnMaxLifeTime > 0 {
			_mssql_store.SetConnMaxLifetime(_mssql_cfg.ConnMaxLifeTime)
		}
		_mssql_store.SetMaxIdleConns(_mssql_cfg.PoolSize)
		_mssql_store.SetMaxOpenConns(_mssql_cfg.PoolSize)
		_mssql_store.AddWrappers(
			database.NewMsSQLTracerWrapper(),
		)
	})
	return _mssql_store
}
